<?php

namespace App\Http\Middleware\Pos;

use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\CommonException;
use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Service\ShopService;
use Closure;
use Illuminate\Http\Request;


class ShopStatusAuth
{
    /**
     * Check Header Id [shopId, brandId]
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string|null ...$guards
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $shopId  = $request->header('shopId');
        $brandId = $request->header('brandId');

        // 开发环境免认证
        if (config('app.env') == 'dev') {
            $brandId = $brandId ?? 1;
            $shopId  = $shopId ?? 1;
        }
        if (empty($brandId) || !is_numeric($brandId)) {
            throw new CommonException(CommonCodeEnum::ERR_BRAND_ID_ERROR);
        }

        if (!isset($shopId) || !is_numeric($shopId)) {
            throw new CommonException(CommonCodeEnum::ERR_SHOP_ID_ERROR);
        }
        $shopInfo = ShopService::getShopAllStatus($shopId);
        if (empty($shopInfo)) {
            throw new ShopException(ShopCodeEnum::ERR_SHOP_ID_NO_EXIST);
        }
        if ($shopInfo['status'] == CodeEnum::SHOP_STATUS_BAN) {
            throw new ShopException(ShopCodeEnum::SHOP_STATUS_BAN);
        }

        if ($shopInfo['status'] == CodeEnum::SHOP_STATUS_PREPARE) {
            throw new ShopException(ShopCodeEnum::SHOP_STATUS_PREPARE);
        }

        return $next($request);
    }
}
